package com.maimao.core.advice;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.ImmutableMap;
import com.maimao.core.enums.AuthEnum;
import com.maimao.core.enums.ExceptionEnum;
import com.maimao.core.enums.RespCode;
import com.maimao.core.exception.AuthException;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.exception.MaiMaoException;
import com.maimao.core.exception.MaiMaoGlobalTransactionException;
import com.maimao.core.model.resp.Result;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import io.seata.core.context.RootContext;
import io.seata.core.exception.RmTransactionException;
import io.seata.core.exception.TransactionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author MaoLin Wang
 * @date 2020/11/30 4:28 下午
 */
@RestControllerAdvice
@Slf4j
public class WebExceptionHandler {

    private static ImmutableMap<Class<? extends Throwable>, ExceptionEnum> exceptions;

    protected static ImmutableMap.Builder<Class<? extends Throwable>, ExceptionEnum> exceptionBuilder = ImmutableMap.builder();

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage(), e);
        return Result.notValid(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(AuthException.class)
    @ResponseBody
    public Result authExcetion(AuthException e) {
        Integer code = e.getCode();
        String msg = e.getMsg();
        e.printStackTrace();
        log.error("authException:{}", msg);
        return Result.fail(code, msg);

    }

    @ExceptionHandler(MaiMaoException.class)
    @ResponseBody
    public Result maiMaoException(MaiMaoException e) {
        ExceptionEnum em = e.getExceptionEnum();
        e.printStackTrace();
        log.error("maiMaoException:{}", e.getMessage());
        return Result.fail(em, false);

    }

    @ExceptionHandler(MaiMaoDaoException.class)
    @ResponseBody
    public Result maiMaoDaoException(MaiMaoDaoException e) {
        e.printStackTrace();
        log.error("MaiMaoDaoException:{}", e.getMessage());
        return Result.fail(RespCode.ERR_TRANSITION);

    }

    /**
     * 参与者提前回滚并关闭了事务 发起者无法提交事务会异常，因为在feign参与端手动回滚了，暂时这样处理feign端抛异常无法回滚的问题
     *
     * @param e
     */
/*    @ExceptionHandler(MaiMaoGlobalTransactionException.class)
    @ResponseBody
    public Result maiMaoGlobalTransactionException(MaiMaoGlobalTransactionException e) {
        e.printStackTrace();
        log.error("MaiMaoGlobalTransactionException:{}", e.getMessage());
        return Result.fail("下单失败");
    }*/

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e) {
        e.printStackTrace();
        log.error("class:{},Exception:{}", e.getClass(), e.getMessage() + "\n" + e.getCause());
        if (exceptions == null) {
            exceptions = exceptionBuilder.build();
        }
        ExceptionEnum em = exceptions.get(e.getClass());
        /*if (e instanceof RmTransactionException || e instanceof TransactionSystemException) {
            //捕获在Feign降级中手动回滚而出现的异常
            return Result.fail("下单失败");
        }*/
        if (StrUtil.isNotBlank(RootContext.getXID())) {
            log.error("分布式事务异常抛出");
            throw new RuntimeException(e.getMessage());
        }
        if (em == null) {
            return Result.fail(RespCode.FAIL, e.getMessage());
        }

        return Result.fail(em, false);
    }

    @ExceptionHandler(HystrixTimeoutException.class)
    @ResponseBody
    public Result handleHystrixTimeoutException(HystrixTimeoutException e) {
        e.printStackTrace();

        return Result.fail("调用超时");
    }

}
